package commonwebgroup.commonwebartifact.CommandHandle;

import commonwebgroup.commonwebartifact.CommonWebArtifact;
import commonwebgroup.commonwebartifact.Helper.HttpHelper;
import commonwebgroup.commonwebartifact.util.CommandUtil;
import commonwebgroup.commonwebartifact.util.StringUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class CommandCenterHandle implements CommandExecutor, TabExecutor {

    private CommonWebArtifact _plugin;
    private HttpHelper _httpHelper;

    public CommandCenterHandle(CommonWebArtifact javaPlugin) {
        _plugin = javaPlugin;
        _httpHelper = new HttpHelper(_plugin);
    }

    private boolean reloadCommand(CommandSender sender) {
        sender = CommandUtil.validCommandSender(sender);
        if (!sender.hasPermission("mcm.reload")) {
            CommandUtil.setErrorMsg(sender, "你没有这个配置重载的权限");
            return false;
        }
        _plugin.reloadPluginConfig();
        CommandUtil.setSuccessMsg(sender, "插件配置重载成功");
        return true;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        sender = CommandUtil.validCommandSender(sender);
        if (Objects.isNull(args)) {
            CommandUtil.setErrorMsg(sender, "args is null");
            return false;
        }

        if (args.length <= 0) {
            CommandUtil.setErrorMsg(sender, "mcm命令长度不足");
            return false;
        }


        //直接过滤特殊指令,目前只有reload
        if (args[0].equalsIgnoreCase("reload")) return reloadCommand(sender);


        //非玩家指令
        if (!(sender instanceof Player player)) return CommandNotPlayerHandle.Execute(sender, command, label, args);

        //玩家指令
        String apiUrl = _plugin.getConfig().getString("api-url");
        String apiKey = _plugin.getConfig().getString("api-key");

        if (StringUtil.isEmpty(apiUrl)) {
            CommandUtil.setErrorMsg(sender, "apiUrl is null");
            return false;
        }

        if (StringUtil.isEmpty(apiKey)) {
            CommandUtil.setErrorMsg(sender, "apiKey is null");
            return false;
        }

        return CommandPlayerHandle.Execute(player, args, apiUrl, apiKey, _httpHelper);

    }


    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
        sender = CommandUtil.validCommandSender(sender);
        List<String> lst = new ArrayList<>(16);
        if (Objects.isNull(args)) {
            return lst;
        }
        if (args.length == 1) {
            lst.add("reload");
            lst.add("pull");
            lst.add("push");

        } else if (args.length == 2) {
            lst.add("item");
        }
        return lst;
    }





}
